<template>
  <div>
    <!-- 三方银行信息维护 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhBankInfoMaintain"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="primary" @click="addHandle">新 增</el-button>
          <multiuse-button size="small" type="primary" :click="exportHandler">导 出</multiuse-button>
          <multiuse-button size="small" type="primary" @click="importHandler">批量导入</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchDealer :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <BaseDialog :visible.sync="visible" :title="drawerTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <!-- 导入 -->
    <BaseDialog :visible.sync="isImport" title="数据导入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ImportFile :rowData="formData" @close="emitCloseHandler2" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getLevelOneArea } from '@/api/cms-common/dealerdata/index';
import { region } from '@/api/cms-common/region'; //行政区域
import { queryList, exportExcel, getFiAccountType, exporturl } from '@/api/omFinanceP/MoneyManage/BankInfoMaintain';
import { exportExcelFile } from '@/utils/index';
import SonModel from './SonModel';
import SearchDealer from '../ownerSeacher';
import ImportFile from './ImportFile';
import { phoneAndSolidify } from '@/utils/validate.js';

export default {
  name: 'BankInfoMaintain',
  mixins: [dictionary,region],

  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      exportLoading: false,
      visible: false,
      isDealer: false,
      isImport: false,
      handleType: '',
      drawerTitle: ''
    };
  },
  components: {
    SonModel,
    ImportFile,
    SearchDealer
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
    this.initProvince();
  },
  created() {
    this.accountType();
  },
  methods: {
    // 所属区域
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },

    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },

    // 资金类型 getFiAccountType
    async accountType() {
      const res = await getFiAccountType({ ignoreAccountTypes: [60361001, 60361002], accountType: 60051001 });
      if (res.resultCode === 200) {
        res.data.map(x => {
          this.topFilterList.find(item => item.fieldName == 'accountTypeId').itemList.push({ text: x.accountTypeName, value: x.id });
        });
      }
    },
    seacherFun() {
      this.isDealer = true;
    },
    addHandle() {
      this.handleType = 'add';
      this.formData = {};
      this.showHandler();
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    detailHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    emitCloseHandler1(val, data) {
      this.isDealer = val;
      let dealerCodes = [];
      let dealerNames = [];
      if (data) {
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.dealerCode = dealerCodes.toString();
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    // 导出
    async exportHandler() {
      // let json = Object.assign({}, { CODE: 'CODE_0000074' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;

          exportExcel(this.fetchParams)
            .then(response => {
              exportExcelFile(response.data, '三方银行信息维护');
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    importHandler() {
      this.isImport = true;
    },
    emitCloseHandler2(val, type) {
      this.isImport = val;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开'
          // unitRender: () => {
          //   return (
          //     <div>
          //       <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
          //     </div>
          //   );
          // }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        // {
        //   type: 'INPUT',
        //   label: '银行名称',
        //   fieldName: 'bankName',
        //   placeholder: '请输入'
        // },
        {
          type: 'INPUT',
          label: '监管公司',
          fieldName: 'superviseCompany',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '监管人',
          fieldName: 'supervisor',
          placeholder: '请输入'
        },
        // {
        //   type: 'SELECT',
        //   label: '状态',
        //   fieldName: 'status',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('1003')
        // },
        {
          type: 'INPUT',
          label: '监管人电话',
          fieldName: 'supervisorPhone',
          maxlength: 11,
          isControls: false,
          placeholder: '请输入',
          rules: [
            {
              validator: phoneAndSolidify,
              trigger: 'blur'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '合格证邮寄地址',
          fieldName: 'certificateMailAddress',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountTypeId',
          placeholder: '请选择',
          itemList: []
        },

        {
          type: 'RANGE_DATE',
          label: '授信到期日期',
          fieldName: 'beginCreditExpireDate|endCreditExpireDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
          initialValue: []
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            // <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
            //       明细
            //     </multiuse-button>
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input'
          // filterItems: this.createRegionsList()
          // render: p => {
          //   let arr = this.createRegionsList();
          //   let str = '';
          //   arr.map(x => {
          //     if (x.value == p.row.provinceId) {
          //       str = x.text;
          //     }
          //   });
          //   return <span>{str}</span>;
          // }
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input'
          // render: p => {
          //   console
          //   let arr = this.createcityList(p.row.provinceId);
          //   let str = '';
          //   arr.map(x => {
          //     if (x.value == p.row.cityId) {
          //       str = x.text;
          //     }
          //   });
          //   return <span>{str}</span>;
          // }
        },

        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商展厅地址',
          dataIndex: 'dealerAddress',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '授信额度',
          dataIndex: 'creditAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true
        },
        {
          title: '授信到期日期',
          dataIndex: 'creditExpireDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '保证金类型',
          dataIndex: 'depositType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p)=>{
            return (<span>{ this.createDictText(p.row.depositType,'2152') }</span>)
          }
        },
        {
          title: '保证金比例(%)',
          dataIndex: 'depositRate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '合格证邮寄地址',
          dataIndex: 'certificateMailAddress',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '监管公司',
          dataIndex: 'superviseCompany',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '监管人',
          dataIndex: 'supervisor',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '监管人电话',
          dataIndex: 'supervisorPhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作时间',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
        // {
        //   title: '状态',
        //   dataIndex: 'status',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //  filterItems: this.createDictList('1003'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.status, '1003')}</span>;
        //   }
        // },
        // {
        //   title: '县区',
        //   dataIndex: 'districtId',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   render: p => {
        //     let arr = this.district(p.row.cityId);
        //     let str = '';
        //     arr.map(x => {
        //       if (x.value == p.row.districtId) {
        //         str = x.text;
        //       }
        //     });
        //     return <span>{str}</span>;
        //   }
        // },

        // {
        //   title: '银行名称',
        //   dataIndex: 'bankName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
      ];
    }
  }
};
</script>